from lib.sensors import dht11
from lib.sensors.oled import ops
from lib.config.index import sensor_config
import framebuf
from lib.clock import custom_timer

p0 = bytearray([0x18, 0x24, 0x24, 0x18, 0x00, 0x00, 0x00, 0x00])
p1 = bytearray([0x00, 0x18, 0x24, 0x24, 0x18, 0x00, 0x00, 0x00])
fb0 = framebuf.FrameBuffer(p0, 8, 8, framebuf.MONO_HLSB)
fb1 = framebuf.FrameBuffer(p1, 8, 8, framebuf.MONO_HLSB)

c_timer = custom_timer.CustomTimer(3)

oled_config = sensor_config.get_sensor("ssd1306")
scl = oled_config["scl"]
sda = oled_config["sda"]
width = oled_config["width"]
height = oled_config["height"]

dht_config = sensor_config.get_sensor("dht11")
dht_pin = dht_config["pin"]
temp = -1
humidity = -1


def show_oled_values():
    global temp, humidity
    _oled = ops.init_oled(scl, sda, width, height)
    ops.text("temp: " + str(temp), 0, 0)
    _oled.blit(fb0, 65, 0)
    ops.text("C", 72, 0)
    ops.text("humidity: " + str(humidity) + "%", 0, 10)
    ops.show()


while True:
    if c_timer.check():
        try:
            (temp, humidity) = dht11.readDHT11(dht_pin)
        except Exception as e:
            print(e)

        show_oled_values()
